<template>
  <a-layout>
    <the-header/>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
    <a-form layout="inline" :model="param">
      <a-form-item>
        <a-input v-model:value="param.loginid" placeholder="学号" required>
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="userQueryById({page: 1, size: pagination.pageSize})">
          查询
        </a-button>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="form()">
          新增
        </a-button>
      </a-form-item>

    </a-form>
  <a-table
      @change="handleTableChange"
      :columns="columns"
      :data-source="users"
      :row-key="record => record.loginid"
      :pagination="pagination"
      >
    <template #name="{ text }">
      <a>{{ text }}</a>
    </template>
    <template #customTitle>
      <span>
        <smile-outlined />
        姓名
      </span>
    </template>
    <template v-slot:action="{text,record}" >


        <div v-if="text.acountnonlocked == true">
          <a-space size="small">
        <a-button  type="danger" @click="locked({loginid:text.loginid,page:pagination.current,size:pagination.pageSize})">
          锁定
        </a-button>
        <a-button disabled type="primary">
          解锁
        </a-button>
            <a-button type="primary" @click="resetPassword(record)">
              重置密码
            </a-button>
            <a-button type = "primary" @click = edit(record)>
              编辑
            </a-button>
            <a-popconfirm
                title="删除后不可恢复,确认删除？"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(record.loginid)">
              <a-button type="danger">
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </div>

        <div v-if="text.acountnonlocked == false">
          <a-space size="small">
          <a-button  disabled type="danger">
            锁定
          </a-button>
          <a-button  type="primary" @click="unlocked({loginid:text.loginid,page:pagination.current,size:pagination.pageSize})">
            解锁
          </a-button>
            <a-popconfirm
                title="删除后不可恢复,确认删除？"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(record.loginid)">
              <a-button type="danger">
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </div>


    </template>
  </a-table>

    </a-layout-content>
    <the-footer/>
  </a-layout>
  <a-modal
      title="用户添加"
      v-model:visible="modalVisible"
      :confirm-loading="modalLoading"
      @ok="add">
    <a-form
        :model="user"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        :rules="rules">
      <a-form-item label="账号"  has-feedback name ="loginid">
        <a-input v-model:value="user.loginid"/>
      </a-form-item>
      <a-form-item label="密码" has-feedback name = "password">
        <a-input v-model:value="user.password"/>
      </a-form-item>
      <a-form-item label="姓名"   has-feedback name = "username">
        <a-input v-model:value="user.username"/>
      </a-form-item>
      <a-form-item label="手机号码" has-feedback name = "phone">
        <a-input v-model:value="user.phone"/>
      </a-form-item>
      <a-form-item label="身份证号码" has-feedback name = "identitynumber">
        <a-input v-model:value="user.identitynumber"/>
      </a-form-item>
    </a-form>

  </a-modal>
  <a-modal
      title="信息编辑"
      v-model:visible="modalVisible1"
      :confirm-loading="modalLoading1"

      @ok="editOk">
    <a-form :model="user"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
            :rules = "rules">
      <a-form-item label="账号"  name = "loginid">
        <a-input v-model:value="user.loginid" :disabled="!!user.loginid"/>
      </a-form-item>
      <a-form-item label="姓名" name="username">
        <a-input v-model:value="user.username"/>
      </a-form-item>
      <a-form-item label="手机号码" name = "phone">
        <a-input v-model:value="user.phone"/>
      </a-form-item>
      <a-form-item label="身份证号码" name = "identitynumber">
        <a-input v-model:value="user.identitynumber"/>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal
      title="重置密码"
      v-model:visible="resetModalVisible"
      :confirm-loading="resetModalLoading"
      @ok="handleResetModalOk"
  >
    <a-form :model="user" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="新密码">
        <a-input v-model:value="user.password"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
import { SmileOutlined, DownOutlined } from '@ant-design/icons-vue';
import { defineComponent,onMounted,ref} from 'vue';
import theHeader from '@/components/the-header.vue';
import theFooter from '@/components/the-footer.vue';
import axios from 'axios';
import {message} from "ant-design-vue";
import router from "@/router";
import {RuleObject} from "ant-design-vue/es/form/interface";
import {Tool} from "../../util/tool";
declare let hexMd5:any;
declare let KEY:any;
const columns = [
  {
    dataIndex: 'username',
    key: 'username',
    slots: { title: 'customTitle', customRender: 'user' },
  },
  {
    title: '学号',
    dataIndex: 'loginid',
    key: 'loginid',
  },
  {
    title: '手机号码',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '身份证号',
    key: 'identitynumber',
    dataIndex: 'identitynumber',
   // slots: {customRender: 'tags'}
  },
  {
    title: 'Action',
    key: 'action',
    slots: {customRender: 'action'}
  },
];




export default defineComponent({

  setup() {
    let checkId = async (rule : RuleObject,value:string)=>{
      if(value === ''){
        return Promise.reject("账号不能为空");
      }else{
        if((value).length > 2 && (value).length < 21){
          return Promise.resolve();
        }
        else{
          return Promise.reject("账号应该在3-20个字节");
        }
      }
    };
    let checkUserName = async (rule:RuleObject,value:string)=>{
      if(value === ''){
        return Promise.reject("姓名不能为空");
      }else{
        if((value).length > 2 && (value).length < 21){
          return Promise.resolve();
        }
        else{
          return Promise.reject("姓名应该在3-20个字节");
        }
      }
    };
    let checkPassword = async (rule:RuleObject,value:string)=>{
      if(value === ''){
        return Promise.reject("密码不能为空");
      }else{
        if((value).length > 2 && (value).length < 21){
          return Promise.resolve();
        }
        else{
          return Promise.reject("密码应该在3-20个字节");
        }
      }
    };
    let checkPhone = async (rule:RuleObject,value:string)=>{
      const pattern = /^1[34578]\d{9}$/;
      if(pattern.test(value)){
        return Promise.resolve();
      }else{
          return Promise.reject("手机号码格式错误");

      }
    };
    let checkIdentityNumber = async (rule:RuleObject,value:string)=>{
      if(value === ''){
        return Promise.reject("身份证不能为空");
      }else{
        if((value).length > 2 && (value).length < 21){
          return Promise.resolve();
        }
        else{
          return Promise.reject("身份证应该在3-20个字节");
        }
      }
    };

    const rules = {
      loginid:[{validator:checkId,trigger:'change'}],
      username:[{validator:checkUserName,trigger:'change'}],
      password:[{validator:checkPassword,trigger:'change'}],
      phone:[{validator:checkPhone,trigger:'blur'}],
      identitynumber:[{validator:checkIdentityNumber,trigger:'change'}]

    };


    const param = ref();
    param.value = {};
    const users = ref();
    const user = ref();
    const pagination = ref({
      current:1,
      pageSize:4,
      total:0
    })
    const locked = (params:any)=>{
      console.log("锁定")
      console.log("loginid",params.loginid);
      axios({
        url:'/api/user/locked',
        method:'post',
        params:{
          loginid:params.loginid
        }
      }).then(
          (response)=> {
            userQuery(({
              page: params.page,
              size: params.size
            }))
          }
      )
    }
    const unlocked=(params:any)=>{
      console.log("解锁")
      console.log("loginid",params.loginid);
      axios({
        url:'/api/user/unlocked',
        method:'post',
        params:{
          loginid:params.loginid
        }
      }).then(
          (response)=> {
            userQuery(({
              page: params.page,
              size: params.size
            }))
          }
      )
    }
    const modalVisible = ref(false);
    const modalLoading = ref(false);


    //表单
    const form=()=>{
      modalVisible.value = true;
      user.value = {}
    }
    //添加用户
    //新增
    const add =()=>{
      modalLoading.value = true;
      user.value.password = hexMd5(user.value.password + KEY);
      console.log("password",user.value.password)
      console.log("user,",user.value)
      console.log("username,",user.value.username)

      axios({
        url:"api/user/register",
        method:"post",
        data:{
          loginid:user.value.loginid,
          password:user.value.password,
          username:user.value.username,
          phone:user.value.phone,
          identitynumber:user.value.identitynumber,
          identity:'学生'
        }}).then(

          (response) =>{
            modalLoading.value = false
            if(response.data.errorCode == 200) {
              modalVisible.value = false;
              userQuery({
                page: pagination.value.current,
                size: pagination.value.pageSize
              });
            }else if(response.data.errorCode == 998){
              message.error("账号存在")
            } else{
              message.error("添加失败")
            }

          }
      )
    }

    //删除学生
    const handleDelete=(loginid:string)=>{
      console.log("loginid",loginid);
      axios.delete("/api/user/delete",{
        params:{
          loginid:loginid
        }
      }).then(
          (response)=> {

            message.success("删除成功")
            userQuery({
              page: pagination.value.current,
              size: pagination.value.pageSize
            })
          }


      )
    }

    onMounted(()=>{
        userQuery({});
    })
    const userQuery=(params:any) =>{
      axios.get("/api/user/list",params).then(
          (response)=>{

            const data = response.data;
            console.log("响应:",response);
            console.log("data:",data);
            if(response.data.errorCode ==2001) {
              message.error("用户未登录");
              router.push("/login")
            }
            else if(response.data.errorCode ==3001){
              message.error("不是管理员无权限");
              router.push("/login")
            }
            else {
              users.value = data;
              console.log("users", users.value);
              //重置分页按钮
              pagination.value.current = params.page;
            }
          }
      );
    };

    const userQueryById=(params:any)=>{

      console.log("loginid:",param.value.loginid)
        axios.get("/api/user/selectLikeId",
            {
              params: {
                loginid: param.value.loginid
              }
            }).then(
            (response)=>{
              console.log("查询",response)
              users.value = response.data

              pagination.value.current = params.page;
            }
        )
    }

    //表格点击页码时触发
    const handleTableChange =(pagination:any)=>{
      console.log("自带分页参数:" + pagination);
      userQuery(({
        page:pagination.current,
        size:pagination.pageSize
      }))
    }

    /**
     * 编辑
     */
    const modalVisible1 = ref(false);
    const modalLoading1 = ref(false);
    const edit = (record: any) => {
      modalVisible1.value = true;
      user.value = Tool.copy(record);
    };

    const editOk = ()=>{
      modalLoading1.value = true;
      //console.log("loginid",user.value.loginid);

      axios({
        url:"/api/user/editAdmin",
        method:"post",
        data:{
          loginid:user.value.loginid,
          username:user.value.username,
          phone:user.value.phone,
          identitynumber:user.value.identitynumber
        }}).then(

          (response) =>{
            modalLoading1.value = false
            if(response.data.errorCode == 200) {
              modalVisible1.value = false;
              userQuery({
                page: pagination.value.current,
                size: pagination.value.pageSize
              });
            }else{
              message.error("修改失败")
            }

          }
      )
    }

    /**
     * 重置密码
     */
    const resetModalVisible = ref(false);
    const resetModalLoading = ref(false);
    const resetPassword = (record: any) => {
      resetModalVisible.value = true;
      user.value = Tool.copy(record);
      user.value.password = null;
    }
    const handleResetModalOk = () => {
      resetModalLoading.value = true;
      user.value.password = hexMd5(user.value.password + KEY);
      axios.post("/api/user/resetPassword", user.value).then((response) => {
        resetModalLoading.value = false;
        const data = response.data; // data = commonResp
        if (data.success) {
          resetModalVisible.value = false;

          // 重新加载列表
          userQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize,
          });
        } else {
          message.error(data.message);
        }
      });
    };
    return {
      columns,
      locked,
      unlocked,
      users,
      pagination,
      handleTableChange,
      param,
      userQueryById,
      user,
      add,
      form,
      modalVisible,
      modalLoading,
      handleDelete,
      rules,
      edit,
      editOk,
      modalVisible1,
      modalLoading1,
      resetModalVisible,
      resetModalLoading,
      resetPassword,
      handleResetModalOk,

    };
  },
  components: {
    SmileOutlined,
    DownOutlined,
    theFooter,
    theHeader,

  },
});
</script>